package com.yycx.module.bus.provider.handler.refund;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.mybatis.interceptor.SaveInterceptor;
import com.yycx.common.mybatis.query.CriteriaSave;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.utils.ApiAssert;
import com.yycx.common.utils.OrderNoUtil;
import com.yycx.module.bus.client.entity.BusPayment;
import com.yycx.module.bus.client.enums.AmountTypeEnum;
import com.yycx.module.bus.provider.service.BusOrderDetailsService;
import com.yycx.module.bus.provider.service.BusPaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 厂家返款保存扩展器
 *
 * @author zyf
 */
@Component("refundPaymentSaveHandler")
public class RefundPaymentSaveHandler implements SaveInterceptor<BusPayment> {

    @Resource
    private OrderNoUtil orderNoUtil;

    @Autowired
    private BusPaymentService paymentService;

    @Resource
    private BusOrderDetailsService orderDetailsService;


    @Override
    public void prepare(CriteriaSave cs, EntityMap entityMap, BusPayment payment) {
        //invoiceId为开票税金的ID
        Long invoiceId = cs.getLong("invoiceId");
        ApiAssert.isNotEmpty("开票ID不能为空", invoiceId);
        BusPayment invoice = paymentService.getById(invoiceId);

        Integer settleType = FlymeUtils.getInteger(invoice.getSettleType(), 1);

        ApiAssert.isNotEmpty("开票税金不能为空", invoice);
        payment.setOrganizationId(invoice.getOrganizationId());
        payment.setCompanyId(invoice.getCompanyId());
        payment.setDeptId(invoice.getDeptId());
        payment.setParentId(invoiceId);
        payment.setPayDate(payment.getAmountDate());
        payment.setPaymentId(IdWorker.getId());
        payment.setTitle("厂家返款");
        payment.setSettleType(settleType);
        payment.setSupplierRetable(invoice.getSupplierRetable());
        payment.setSupplierId(invoice.getSupplierId());
        payment.setAmountType(AmountTypeEnum.Refund.getCode());
        payment.setAmount(invoice.getSupplierRetable());
        String orderNo = orderNoUtil.getIncrementNum();
        payment.setPaymentNo("FK" + orderNo);
        payment.setInvoiceUnitId(invoice.getInvoiceUnitId());
        //开票金额
        payment.setInvoiceAmount(invoice.getInvoiceAmount());
        payment.setUserId(OpenHelper.getUserId());
        payment.setNickName(OpenHelper.getNickName());
        payment.setPaymentState(CommonConstants.INT_0);
    }

    @Override
    public void complete(CriteriaSave cs, EntityMap params, BusPayment entity) {
        //关联返款ID
        orderDetailsService.updateFankuanId(entity,entity.getParentId());
    }


}
